﻿using System.IO;
using System.Linq;
using EasyTagWinForm.Model;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;

namespace EasyTagWinForm
{
  internal class TagCacheHandler
  {
    private readonly string TagCacheFileName = "_tagCache.json";
    public TagCacheHandler(string fileDir, List<TagInfo> tagInfos)
    {
      FileDir = fileDir;
      TagInfos = tagInfos;
      TagCacheFilePath = FileDir + "/" + TagCacheFileName;
      HasCache = SetHasCache();
      //if don't have cache file
      if (!HasCache)
      {
        CreateTagCacheFile();
        HasCache = true;
      }
      else
      {

      }
    }

    public string FileDir { get; set; }
    public bool HasCache { get; set; }
    public string TagCacheFilePath { get; set; }

    public List<TagInfo> TagInfos { get; set; }
    public void AddTagCacheFile()
    {

    }

    public bool CreateTagCacheFile()
    {
      try
      {
        using (FileStream fs = new FileStream(TagCacheFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
        {
          using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
          {
            string tagInfosJson = JsonConvert.SerializeObject(TagInfos);
            sw.Write(tagInfosJson);
          }
          return true;
        }
      }
      catch
      {
        return false;
      }
      finally
      {

      }

    }

    public bool SetHasCache()
    {
      DirectoryInfo dir = new DirectoryInfo(FileDir);
      FileInfo[] fileinfo = dir.GetFiles(); //取得所有文件
      if (fileinfo.Where(e => e.Name == TagCacheFileName).Count() > 0)
      {
        return true;
      }
      else
      {
        return false;
      }
    }
  }
}